package com.doodle.common.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * fragment间传递消息的工具
 * @author mason
 */
public class ResultNotifyHelper {
	
	/**
	 * 发送者要包含此对象实例
	 * @author mason
	 */
	public static class ResultBroadCaster {
		
		private List<ResultReceiver> mReceivers = new ArrayList<ResultReceiver>();
		private boolean mIsResultOk = false;
		private Object mResult = null;
		
		/**
		 * 用于设置receiver初始值(如果broadCaster的结果已经获取到，receiver才创建，这时就子项主动来读取结果)
		 * 注：一定要在addReceiver，设置之后调用。建议放在onCreateActivity的最后来执行
		 * 注：要使此函数有效，需调用broadcastResult()来配合. 
		 * 例：见PurchasedPagerFragment
		 * @param receiver
		 */
		public void onReceiverStarted(ResultReceiver receiver) {
			if (!mIsResultOk) {
				return;
			}
			for (ResultReceiver r : mReceivers) {
				if (r == receiver) {
					receiver.onResultFinished(mResult);
				}
			}
		}
		
		public List<ResultReceiver> getReceivers() {
			return mReceivers;
		}
		
		/**
		 * 发送者在获得结果后要调用一下此函数
		 * @param result
		 */
		public void broadcastResult(Object result) {
			mResult = result;
			mIsResultOk = true;
			
			for (ResultReceiver rr : mReceivers) {
				rr.onResultFinished(result);
			}
		}
		
		public void addReceiver(ResultReceiver receiver) {
			mReceivers.add(receiver);
		}
		
		public void removeReceiver(ResultReceiver receiver) {
			mReceivers.remove(receiver);
		}
	}
	
	public static void onReceiverStarted(ResultReceiver receiver) {
		ResultBroadCaster broadcaster = receiver.findResultBroadCaster();
		if (broadcaster != null) {
			broadcaster.onReceiverStarted(receiver);
		}
	}
	
	public static void removeReceiver(ResultReceiver receiver) {
		ResultBroadCaster broadcaster = receiver.findResultBroadCaster();
		if (broadcaster != null) {
			broadcaster.removeReceiver(receiver);
		}
	}
	
	public static void addReceiver(ResultReceiver receiver) {
		ResultBroadCaster broadcaster = receiver.findResultBroadCaster();
		if (broadcaster != null) {
			broadcaster.addReceiver(receiver);
		}
	}
	
	/**
	 * 接收者要实现此接口
	 * @author mason
	 */
	public static interface ResultReceiver {
		public abstract void onResultFinished(Object result);
		public abstract ResultBroadCaster findResultBroadCaster();
	}
}
